package com.boot.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.result.Result;
import com.boot.user.dto.DeduceDTO;
import com.boot.user.pojo.User;
import com.boot.service.UserService;
import com.boot.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
* @author liyan
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-05-25 15:55:56
*/
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    private final UserMapper userMapper;

    @Override
    public Result getUserById(long id) {
        User user = baseMapper.selectById(id);
        return Result.success(user);
    }

    @Override
    public Result deduce(DeduceDTO deduceDTO) {
        User user = userMapper.selectById(deduceDTO.getUserId());
        if (user == null || user.getStatus() != 1) {
            return Result.build(500,"用户不存在或被禁用", null);
        }
        if (user.getBalance().compareTo(deduceDTO.getAmount()) < 0) {
            return Result.build(500,"余额不足", null);
        }
        user.setBalance(user.getBalance().subtract(deduceDTO.getAmount()));
        int row = userMapper.updateById(user);
        if (row == 0) {
            return Result.build(500,"更新用户余额失败", null);
        }
        return Result.success(null);
    }
}




